package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    /** 微信服务接口地址 */
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(UserLoginDTO loginDTO) {
        // 1.调用微信接口(HttpClient 发送请求)，实现登录操作
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", loginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");

        String result = HttpClientUtil.doGet(WX_LOGIN_URL, paramMap);
        log.info("微信登录，结果:{}", result);
        if(StringUtils.isEmpty(result)) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        JSONObject jsonObject = JSON.parseObject(result);
        // 获取微信用户唯一标识
        String openid = jsonObject.getString("openid");
        if(StringUtils.isEmpty(openid)) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 2.用户第一次访问小程序，自动注册
        User user = userMapper.getByOpenid(openid);
        if(ObjectUtils.isEmpty(user)) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        // 3.返回数据
        return user;
    }
}
